package com.frog.chinanews;

import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import com.frog.chinanews.activity.ContentActivity;
import com.frog.rss.RSSHelper;
import com.frog.rss.domain.RSSItem;
import com.frog.rss.facade.RSSFacade;
import com.frog.rss.service.LoadRSSItemsSerivce;

public class MainActivity extends Activity {
	RSSFacade rssFacade = new RSSFacade();
	RSSItem currentRssItem;

	// UI
	private ListView listView;
	// data
	private List<RSSItem> rssItems;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		// start load-rss-service
		Intent loadRssIntent = new Intent(MainActivity.this,
				LoadRSSItemsSerivce.class);
		startService(loadRssIntent);
		// init UIs
		listView = (ListView) findViewById(R.id.rssItems);
		// init rss data `````
		rssItems = rssFacade.loadRSSItemsFromDB(MainActivity.this);
		listView.setAdapter(new SimpleAdapter(MainActivity.this, RSSHelper
				.rssItemsToListMap(rssItems), R.layout.listitem, new String[] {
				RSSItem.TITLE, RSSItem.PUBDATE }, new int[] { R.id.itemTitle,
				R.id.itemDescription }));
		listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				LinearLayout itemContainer = (LinearLayout) arg1;
				ImageView star = (ImageView) itemContainer
						.findViewById(R.id.starView);
				star.setImageResource(R.drawable.btn_star_big_on_selected);
				return true;
			}
		});
		listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				currentRssItem = rssItems.get(position);
				Intent contentIntent = new Intent(MainActivity.this,
						ContentActivity.class);
				contentIntent.putExtra("rssItem", currentRssItem);
				startActivity(contentIntent);
			}
		});
	}

	private void refreshListView() {

	}

	public class GetNewRssHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			String status = msg.getData().getString("status");
			if ("updated".equals(status)) {
				refreshListView();
			}
		}
	}
}